<template>
	<main-content
		:tableHeight.sync="tableHeight"
		:otherDependenComponents="otherDependenComponents"
	>
		<template slot="query">
			<el-form
				ref="ruleForm"
				:model="queryData"
				label-width="100px"
				label-suffix=":"
				:inline="true"
			>
				<el-form-item :label="`商品类型`">
					<el-select
						v-model="queryData.goodsTypeList"
						clearable
						:placeholder="`${$t('common.select_all')}`"
						style="width:220px"
						multiple
					>
						<el-option
							v-for="item in productTypeArr"
							:key="item.code"
							:label="item.description"
							:value="item.code"
						></el-option>
					</el-select>
				</el-form-item>
				<el-form-item :label="`商品名称`">
					<el-input
						v-model.trim="queryData.goodsName"
						v-input="{ name: 'symbols' }"
						clearable
						:placeholder="`${$t('common.please_enter')}`"
					></el-input>
				</el-form-item>
				<el-form-item :label="`商品状态`">
					<el-select
						v-model="queryData.status"
						clearable
						:placeholder="`${$t('common.select_all')}`"
						style="width:150px"
					>
						<el-option
							v-for="item in productStatusArr"
							:key="item.code"
							:label="item.description"
							:value="item.code"
						></el-option>
					</el-select>
				</el-form-item>
				<el-form-item :label="`上架状态`">
					<el-select
						v-model="queryData.shelvesStatus"
						clearable
						:placeholder="`${$t('common.select_all')}`"
						style="width:150px"
					>
						<el-option
							v-for="item in shelvesStatusStatusArr"
							:key="item.code"
							:label="item.description"
							:value="item.code"
						></el-option>
					</el-select>
				</el-form-item>
				<el-form-item label="商品时效">
					<el-input
						v-model="queryData.durationMin"
						size="medium"
						:placeholder="$t('common.minimum')"
						style="width: 120px"
						maxLength="15"
						v-input="{ name: 'int' }"
						name="durationMin"
						clearable
						@blur="
							handleAmount(
								queryData,
								1,
								'durationMin',
								'durationMax',
								$t('member.check_min_tips')
							)
						"
					></el-input>

					-

					<el-input
						v-model="queryData.durationMax"
						size="medium"
						:placeholder="$t('common.maximum')"
						style="width: 120px"
						maxLength="15"
						v-input="{ name: 'int' }"
						name="durationMax"
						clearable
						@blur="
							handleAmount(
								queryData,
								2,
								'durationMin',
								'durationMax',
								$t('member.check_max_tips')
							)
						"
					></el-input>
				</el-form-item>
				<el-form-item label="价格">
					<el-input
						v-model="queryData.priceMin"
						size="medium"
						:placeholder="$t('common.minimum')"
						style="width: 120px"
						maxLength="15"
						v-input="{ name: 'onlyTwoNum' }"
						name="priceMin"
						clearable
						@blur="
							handleAmount(
								queryData,
								1,
								'priceMin',
								'priceMax',
								$t('member.check_min_tips')
							)
						"
					></el-input>

					-

					<el-input
						v-model="queryData.priceMax"
						size="medium"
						:placeholder="$t('common.maximum')"
						style="width: 120px"
						maxLength="15"
						v-input="{ name: 'onlyTwoNum' }"
						name="priceMax"
						clearable
						@blur="
							handleAmount(
								queryData,
								2,
								'priceMin',
								'priceMax',
								$t('member.check_max_tips')
							)
						"
					></el-input>
				</el-form-item>
				<el-form-item>
					<el-button
						type="primary"
						icon="el-icon-search"
						:disabled="loading"
						:loading="loading"
						size="medium"
						@click="handleSearch"
					>
						{{ $t('dxn.card_ables_list.search') }}
					</el-button>
					<el-button
						icon="el-icon-refresh-right"
						size="medium"
						@click="reset"
					>
						{{ $t('dxn.card_ables_list.reset') }}
					</el-button>
					<el-button
						v-if="hasPermission('90870112')"
						type="warning"
						icon="el-icon-download"
						size="medium"
						:loading="exportBtnLoading"
						@click="exportExcel"
					>
						{{ $t('dxn.card_ables_list.export_excel') }}
					</el-button>
				</el-form-item>
			</el-form>
			<div>
				<el-button
					v-if="hasPermission('90870113')"
					type="primary"
					:disabled="isEdit || loading || addDisabled"
					size="mini"
					@click="handleAdd"
				>
					新增
				</el-button>
			</div>
		</template>
		<template slot="content">
			<el-table
				ref="refTable"
				v-loading="loading"
				element-loading-spinner="el-icon-loading"
				size="mini"
				class="small-size-table"
				border
				:data="list"
				style="width: 100%"
				:max-height="tableHeight"
				:header-cell-style="getRowClass"
				highlight-current-row
				header-align="center"
			>
				<el-table-column
					type="index"
					label="序号"
					width="80"
					align="center"
				/>
				<el-table-column
					:label="`商品类型`"
					:min-width="columnWidth.goodsType"
					align="center"
					show-overflow-tooltip
				>
					<template slot-scope="scope">
						<el-select
							v-if="isAddSelectRow(scope.$index)"
							v-model="submitForm.goodsType"
							style="width: 120px"
							@change="handleChangeGoodsType"
							name="submitFormGoodsType"
						>
							<el-option
								v-for="(item, key) in apiGoodsTypeArr"
								:key="key + Math.random()"
								:label="item.description"
								:value="item.code"
							></el-option>
						</el-select>
						<span v-else>
							{{ scope.row.typeName || '-' }}
						</span>
					</template>
				</el-table-column>
				<el-table-column
					label="商品编号"
					min-width="130"
					align="center"
					show-overflow-tooltip
				>
					<template slot-scope="scope">
						<span v-if="isAddSelectRow(scope.$index)">
							{{ submitForm.goodsCode || '-' }}
						</span>
						<span v-else>
							{{ scope.row.goodsCode || '-' }}
						</span>
					</template>
				</el-table-column>
				<el-table-column
					:label="`商品名称`"
					:min-width="columnWidth.goodsName"
					align="center"
					show-overflow-tooltip
				>
					<template slot-scope="scope">
						<el-select
							v-if="isAddSelectRow(scope.$index)"
							v-model="submitFormGoodsName"
							style="width: 140px"
							@change="handleChangeGoodsName"
							name="submitFormGoodsName"
						>
							<el-option
								v-for="(item, key) in apiGoodsTypeProductArr"
								:key="key + Math.random()"
								:label="item.description"
								:value="item.code"
							></el-option>
						</el-select>

						<span v-else>
							{{ scope.row.goodsName || '-' }}
						</span>
					</template>
				</el-table-column>
				<el-table-column
					:label="`商品状态`"
					min-width="100"
					align="center"
					show-overflow-tooltip
				>
					<template slot-scope="scope">
						<span v-if="isAddSelectRow(scope.$index)">
							{{
								getTypeName(submitForm.status, productStatusArr)
							}}
						</span>
						<span v-else>
							{{ scope.row.statusName || '-' }}
						</span>
					</template>
				</el-table-column>
				<el-table-column
					:label="`商品时效`"
					:min-width="columnWidth.duration"
					align="center"
					show-overflow-tooltip
				>
					<template slot-scope="scope">
						<template
							v-if="
								isAddSelectRow(scope.$index) ||
									isEditSelectRow(scope.$index)
							"
						>
							<el-input
								v-model="submitForm.duration"
								style="width: 70px;"
								:maxlength="4"
								id="submitFormDuration"
								:disabled="durationPermanentFlag"
								v-input="{ name: 'intp' }"
								@blur="handleBlurCheckGoodsDuration(scope.row)"
							/>
							<el-checkbox
								label="永久"
								v-model="durationPermanentFlag"
								@change="handleChangeDurationPermanent"
							></el-checkbox>
						</template>
						<span v-else>
							{{ getDurationNameFunc(scope.row.duration) }}
						</span>
					</template>
				</el-table-column>
				<el-table-column
					:label="`价格`"
					:min-width="columnWidth.price"
					align="center"
					show-overflow-tooltip
				>
					<template slot-scope="scope">
						<el-input
							v-if="
								isAddSelectRow(scope.$index) ||
									isEditSelectRow(scope.$index)
							"
							v-model="submitForm.price"
							style="width: 100px;"
							:maxlength="15"
							v-input="{ name: 'float', num: '2' }"
						/>
						<span v-else>
							{{ scope.row.price }}
						</span>
						<span>$</span>
					</template>
				</el-table-column>
				<el-table-column
					:label="`上架状态`"
					:min-width="columnWidth.shelvesStatus"
					align="center"
				>
					<template slot-scope="scope">
						<el-select
							v-if="
								isAddSelectRow(scope.$index) ||
									isEditSelectRow(scope.$index)
							"
							v-model="submitForm.shelvesStatus"
							style="width:80px"
						>
							<el-option
								v-for="item in shelvesStatusStatusArr"
								:key="item.code"
								:label="item.description"
								:value="item.code"
							></el-option>
						</el-select>
						<span v-else>
							{{ scope.row.shelvesStatusName || '-' }}
						</span>
					</template>
				</el-table-column>
				<el-table-column
					label="创建时间"
					min-width="160"
					align="center"
					show-overflow-tooltip
				>
					<template slot-scope="scope">
						{{ scope.row.createdAt || '-' }}
					</template>
				</el-table-column>
				<el-table-column
					:label="`创建人`"
					min-width="120"
					align="center"
					show-overflow-tooltip
				>
					<template slot-scope="scope">
						{{ scope.row.createdBy || '-' }}
					</template>
				</el-table-column>
				<el-table-column
					label="最后操作时间"
					min-width="160"
					align="center"
					show-overflow-tooltip
				>
					<template slot-scope="scope">
						{{ scope.row.updatedAt || '-' }}
					</template>
				</el-table-column>
				<el-table-column
					:label="`最后操作人`"
					min-width="120"
					align="center"
					show-overflow-tooltip
				>
					<template slot-scope="scope">
						{{ scope.row.updatedBy || '-' }}
					</template>
				</el-table-column>
				<el-table-column
					:label="`${$t('dxn.card_ables_list.operate')}`"
					min-width="160"
					fixed="right"
					align="center"
				>
					<template slot-scope="scope">
						<template
							v-if="
								isAddSelectRow(scope.$index) ||
									isEditSelectRow(scope.$index)
							"
						>
							<el-button
								type="text"
								class="action-button"
								:disabled="submitLoading"
								@click="handleCancel"
							>
								{{ $t('common.cancel') }}
							</el-button>
							<el-button
								type="text"
								class="action-button"
								:loading="submitLoading"
								@click="handleSubmit"
							>
								{{ $t('common.save') }}
							</el-button>
						</template>
						<template v-else>
							<template v-if="hasPermission('90870115')">
								<el-button
									v-if="scope.row.shelvesStatus === 1"
									type="text"
									class="action-button"
									:disabled="isEdit"
									:loading="
										submitLoading &&
											currentIndex === scope.$index
									"
									@click="handleUpDown(2, scope.row.id)"
								>
									上架
								</el-button>
								<el-button
									v-else
									type="text"
									class="action-button"
									:disabled="isEdit"
									:loading="
										submitLoading &&
											currentIndex === scope.$index
									"
									@click="handleUpDown(1, scope.row.id)"
								>
									下架
								</el-button>
							</template>
							<el-button
								v-if="hasPermission('90870114')"
								type="text"
								class="action-button"
								:disabled="isEdit"
								@click="handleEdit(scope)"
							>
								编辑
							</el-button>
						</template>
					</template>
				</el-table-column>
			</el-table>
			<el-pagination
				v-show="!!total"
				class="pageValue"
				:current-page.sync="pageNum"
				background
				layout="total, sizes,prev, pager, next, jumper"
				:page-size="pageSize"
				:page-sizes="$store.getters.pageSizes"
				:total="total"
				:pager-count="9"
				@current-change="handleCurrentChange"
				@size-change="handleSizeChange"
			></el-pagination>
		</template>
	</main-content>
</template>

<script>
import list from '@/mixins/list'
import MainContent from '@/components/MainContent/index.vue'
import {
	productStatusArr,
	shelvesStatusStatusArr,
	getDurationNameFunc,
	durationPermanentNum
} from '@/views/dxn/shopManager/components/constants'

export default {
	components: {
		MainContent
	},
	mixins: [list],
	data() {
		return {
			loading: false,
			list: [],
			exportBtnLoading: false,
			tableHeight: 480,
			otherDependenComponents: ['wrap'],
			queryData: {
				status: '',
				goodsName: '',
				goodsTypeList: [],
				shelvesStatus: '',
				priceMin: undefined,
				priceMax: undefined,
				durationMin: undefined,
				durationMax: undefined
			},
			apiGoodsTypeProductArr: [],
			apiGoodsTypeArr: [],
			allGoodsTypeProductMap: new Map(),
			isEdit: false,
			isAdd: false,
			addDisabled: false,
			submitForm: { goodsType: undefined },
			submitFormGoodsName: undefined,
			submitGoodsCode: undefined,
			durationPermanentFlag: false,
			isCheckRepeat: true,
			submitLoading: false,
			currentIndex: undefined,
			productStatusArr,
			productTypeArr: [],
			shelvesStatusStatusArr,
			durationPermanentNum
		}
	},
	computed: {
		columnWidth() {
			if (this.isAdd) {
				return {
					goodsType: 180,
					goodsName: 200,
					duration: 160,
					price: 150,
					shelvesStatus: 110
				}
			} else if (this.isEdit) {
				return {
					goodsType: 135,
					goodsName: 135,
					duration: 160,
					price: 150,
					shelvesStatus: 110
				}
			} else {
				return {
					goodsType: 135,
					goodsName: 135,
					duration: 100,
					price: 100,
					shelvesStatus: 100
				}
			}
		}
	},
	created() {
		this.getProductTypeArr()
	},
	methods: {
		// 获取商品类型配置
		getProductTypeArr() {
			this.productTypeArr = []
			this.$api
				.getBackendEnumListBend({ code: 1001 })
				.then((res) => {
					this.productTypeArr = res?.data || []
				})
				.catch(() => {})
		},
		getDurationNameFunc,
		// 同商品商品时效重复检查
		async handleBlurCheckGoodsDuration(row) {
			// 避免失焦和获取焦点死循环
			if (!this.isCheckRepeat) {
				return false
			}
			const params = {
				id: row?.id,
				goodsCode: row?.goodsCode,
				duration: this.submitForm.duration
			}
			if (this.isEmptyOrNullOrUndefined(params.duration)) {
				return false
			}
			try {
				const res = await this.$api.getMallGoodsIfExistBend(params)
				if (res?.data?.id !== undefined) {
					this.$message.closeAll()
					this.$message.warning('该商品的商品时效重复')
					document.getElementById('submitFormDuration').focus()
					return true
				}
			} catch (err) {
				return false
			}
			return false
		},
		// 查询所有开启的商品 { status: 2 }
		async getGoodsListByGoodsType() {
			this.addDisabled = true
			this.allGoodsTypeProductMap = new Map()
			this.apiGoodsTypeArr = []
			await this.$api
				.getMallProductNoPageListBend({})
				.then((res) => {
					if (Array.isArray(res.data)) {
						res.data.forEach((item) => {
							const goodsItem = {
								code: item.goodsCode,
								description: item.goodsName,
								status: item.status
							}
							if (
								this.allGoodsTypeProductMap.get(item.goodsType)
							) {
								this.allGoodsTypeProductMap
									.get(item.goodsType)
									.push(goodsItem)
							} else {
								this.allGoodsTypeProductMap.set(
									item.goodsType,
									[goodsItem]
								)
								this.apiGoodsTypeArr.push({
									code: item.goodsType,
									description: item.goodsTypeName
								})
							}
						})
					}
					this.addDisabled = false
				})
				.catch(() => {
					this.addDisabled = false
				})
		},
		// 选择永久
		handleChangeDurationPermanent() {
			if (this.durationPermanentFlag) {
				this.submitForm.duration = ''
			}
		},
		// 获取默认的值
		setDefaultGoodsAndGoodsType(goodsType) {
			this.apiGoodsTypeProductArr =
				this.allGoodsTypeProductMap.get(goodsType) || []

			const item = this.apiGoodsTypeProductArr[0] || {}
			this.submitForm.goodsType = item?.code ? goodsType : ''
			this.setSubmitFormInfo(item)
		},
		// 获取产品信息
		setSubmitFormInfo(item) {
			this.submitForm.goodsCode = item?.code || ''
			this.submitForm.goodsName = item?.description || ''
			this.submitForm.status = item?.status || 2
			this.submitFormGoodsName = this.submitForm.goodsCode
		},
		// 商品名称变化
		handleChangeGoodsName(val) {
			const item = this.apiGoodsTypeProductArr.find(
				(item) => item.code == val
			)
			this.setSubmitFormInfo(item || {})
		},
		// 商品类型变化
		handleChangeGoodsType(val) {
			this.setDefaultGoodsAndGoodsType(val)
		},
		// 新增
		async handleAdd() {
			await this.getGoodsListByGoodsType()
			this.currentIndex = 0
			this.durationPermanentFlag = false
			this.isAdd = true
			this.isEdit = true
			this.submitForm = {
				goodsType: '', // 默认商品类型
				goodsName: '',
				goodsCode: '',
				status: '', // 默认读取该商品的状态
				price: '',
				duration: '',
				shelvesStatus: 2 // 2默认上架
			}
			this.setDefaultGoodsAndGoodsType(1)
			this.submitGoodsCode = this.submitForm.goodsCode
			this.list.unshift(this.submitForm)
			this.$refs.refTable.setCurrentRow(this.list[0])
			this.$refs.refTable.bodyWrapper.scrollTop = 0
		},
		// 修改
		handleEdit(scope) {
			this.currentIndex = scope.$index
			this.isEdit = true
			this.submitForm = {
				id: scope.row.id,
				duration: scope.row.duration,
				price: scope.row.price,
				shelvesStatus: scope.row.shelvesStatus
			}
			if (scope.row.duration === this.durationPermanentNum) {
				this.submitForm.duration = ''
				this.durationPermanentFlag = true
			}
			this.submitGoodsCode = scope.row.goodsCode
		},
		// 提交
		async handleSubmit() {
			const params = { ...this.submitForm }
			if (this.durationPermanentFlag) {
				params.duration = this.durationPermanentNum
			}
			if (this.isAdd) {
				if (this.isEmptyOrNullOrUndefined(params.goodsType)) {
					this.$message.closeAll()
					this.$message.warning('商品类型未配置，请检查')
					return
				}
				if (this.isEmptyOrNullOrUndefined(params.goodsName)) {
					this.$message.closeAll()
					this.$message.warning('商品名称未配置，请检查')
					return
				}
			}
			if (this.isEmptyOrNullOrUndefined(params.duration)) {
				this.$message.closeAll()
				this.$message.warning('商品时效未配置，请检查')
				return
			}
			if (this.isEmptyOrNullOrUndefined(params.price)) {
				this.$message.closeAll()
				this.$message.warning('价格未配置，请检查')
				return
			}
			if (Number(params.duration) === 0) {
				this.$message.closeAll()
				this.$message.warning('商品时效不能为0')
				return
			}
			if (Number(params.price) === 0) {
				this.$message.closeAll()
				this.$message.warning('价格不能为0')
				return
			}
			const submitApi = this.isAdd
				? 'addMallGoodsBend'
				: 'updateMallGoodsBend'
			this.submitLoading = true
			this.$api[submitApi](params)
				.then((res) => {
					this.submitLoading = false
					if (res?.code === 200) {
						this.$message.success('保存成功')
						this.resetSubmitForm()
						this.loadData()
					}
				})
				.catch(() => {
					this.submitLoading = false
				})
		},
		// 取消
		handleCancel() {
			this.isCheckRepeat = false
			this.$confirm(
				'是否取消本次编辑操作？',
				this.$t('common.components.tip'),
				{
					confirmButtonText: this.$t('common.sure'),
					cancelButtonText: this.$t('common.cancel'),
					type: 'warning'
				}
			)
				.then(() => {
					this.resetSubmitForm()
				})
				.catch(() => {
					this.$message({
						type: 'info',
						message: '已取消'
					})
				})
				.finally(() => {})
		},
		// 重置submit
		resetSubmitForm() {
			this.currentIndex = undefined
			this.durationPermanentFlag = false
			this.submitFormGoodsName = undefined
			this.submitForm = { goodsType: undefined, goodsName: undefined }
			this.isEdit = false
			if (this.isAdd) {
				this.list.shift()
				this.isAdd = false
			}
		},
		isEmptyOrNullOrUndefined(val) {
			return val === '' || val === null || val === undefined
		},
		isAddSelectRow(index) {
			return this.isAdd && this.currentIndex === index
		},
		isEditSelectRow(index) {
			return this.isEdit && this.currentIndex === index
		},
		// 上架下架1:下架，2：上架
		handleUpDown(val, id) {
			this.$confirm(
				`${
					val === 1
						? '是否对该商城商品进行下架操作？确认后更新上架状态为“下架”'
						: '是否对该商城商品进行上架操作？确认后更新上架状态为“上架”'
				}`,
				this.$t('common.components.tip'),
				{
					confirmButtonText: this.$t('common.sure'),
					cancelButtonText: this.$t('common.cancel'),
					type: 'warning'
				}
			)
				.then(() => {
					const params = {
						id: id,
						shelvesStatus: val
					}
					this.submitLoading = true
					this.$api
						.updateMallGoodsBend(params)
						.then((res) => {
							this.submitLoading = false
							if (res?.code === 200) {
								this.$message.success(
									val === 1 ? '下架成功' : '上架成功'
								)
								this.loadData()
							}
						})
						.catch(() => {
							this.submitLoading = false
						})
				})
				.catch(() => {
					this.$message({
						type: 'info',
						message: '已取消'
					})
				})
		},
		getCurrentParams() {
			const params = {
				...this.queryData
			}
			if (!params.goodsTypeList?.length) {
				params.goodsTypeList = undefined
			}
			return params
		},
		loadData() {
			const params = this.getParams(this.getCurrentParams())
			this.loading = true
			this.list = []
			this.$api
				.getMallGoodsListBend(params)
				.then((res) => {
					this.loading = false
					const { record = [], totalRecord } = res.data || {}
					this.list = record
					this.total = totalRecord || 0
				})
				.catch(() => {
					this.loading = false
				})
		},
		handleSearch() {
			this.resetSubmitForm()
			this.pageNum = 1
			this.loadData()
		},
		reset() {
			this.resetSubmitForm()
			Object.keys(this.queryData).forEach((key) => {
				if (Array.isArray(this.queryData[key])) {
					this.queryData[key] = []
				} else {
					this.queryData[key] = undefined
				}
			})
			this.pageNum = 1
			this.loadData()
		},
		exportExcel() {
			const params = this.getParams(this.getCurrentParams())
			params.pageSize = undefined
			params.pageNum = undefined
			this.exportBtnLoading = true
			this.exportExcelPublic({
				api: 'exportMallGoodsListBend',
				params
			}).finally(() => {
				this.exportBtnLoading = false
			})
		},
		// 跳转
		handleJump(obj) {
			this.$router.push(obj)
		}
	}
}
</script>
<style lang="scss" scoped>
.game-container {
	margin: 0px 16px 50px 16px;
}
.text-click {
	color: #409eff;
	cursor: pointer;
}
.action-button {
	min-width: 30px !important;
}
</style>
